<?php

namespace Home\Controller;

use Think\Controller;

class AjaxController extends Controller {

    public function addToCollect() {//1商品 2店铺
        $data['pid'] = I("post.id");
        $data['mtype'] = I("post.mtype");
        $info = M("collects")->field("id")->where("pid = " . $data['pid'] . " AND mtype = " . $data['mtype'] . "")->find();
        if ($info) {
            M("collects")->where("pid = " . $data['pid'] . " AND mtype = " . $data['mtype'] . "")->limit(1)->delete();
        } else {
            $data['uid'] = session("userid");
            $rs = M("collects")->add($data);
        }
        echo $rs;
    }

    public function recommendShopsSub() {
        $data['name'] = I("post.name");
        $data['phone'] = I("post.phone");
        $data['addr'] = I("post.addr");
        $data['uid'] = session("userid");
        $data['addtime'] = time();
        M("shop_apply")->add($data);
    }

    public function checkMobileSendCode() {
        $code = I('post.code');
        $info = M("codes")->field("id")->where("account='" . session("userid") . "' AND rand = '" . $code . "'")->find();
        if ($info['id'] > 0) {
            echo "true";
        } else {
            echo "false";
        }
    }

    function bindPhoneConfirm() {
        $code = I('post.code');
        $data['phone'] = I('post.phone');
        if (strtolower($code) == $_SESSION["helloweba_gg"]) {
            $info = M("user")->field("id")->where("phone='" . $data['phone'] . "'")->find();
            if (!$info) {
                $user = M("user")->field("phone")->where("id='" . session('userid') . "'")->find();
                if ($user['phone'] == '') {
                    $config = getTableConfig();
                    $money = $config['points_bindPhone'];
                    M("user")->where("id=" . session('userid') . "")->setInc('money', $money); //setInc加
                    addLog("bind_phone", $money, session("userid"), "绑定手机获得" . $money . "积分", 5, 1);
                    echo $money;
                }
                M("user")->where("id = " . session("userid") . "")->save($data);
                M("codes")->where("account='" . session("userid") . "'")->delete();
            } else {
                echo -1;
            }
        }
    }

    function sendMobileBind() {
        $code = I('post.code');
        $phone = I('post.phone');
        if (strtolower($code) == $_SESSION["helloweba_gg"]) {
            $data['addtime'] = time();
            $data['rand'] = rand(100000, 999999);
            $info = M('codes')->field("id")->where("account = " . session("userid") . " AND mtype = 2")->find();
            if ($info['id'] > 0) {
                M('codes')->where("id = " . $info['id'] . "")->save($data);
            } else {
                $data['account'] = session("userid");

                $data['mtype'] = 2;
                M('codes')->add($data);
            }
            echo getMessageResult(sendMessagesCode($code, $phone, session("userid")));
        }
    }

    public function signDay() {
        $data['addtime'] = strtotime(date("Y-m-d 00:00:00"));
        $data['uid'] = session('userid');
        $info = M('sign')->field("id")->where("addtime = " . $data['addtime'] . " AND uid = " . $data['uid'] . " AND status = 0")->find();

        if (empty($info)) {
            $config = getTableConfig();
            $data['money'] = $config['points_daysign'];
            $lastid = M('sign')->add($data);
            addLog("day_sign", $data['money'], session("userid"), "每日签到获得" . $data['money'] . "积分", 5, 1);
            if ($lastid > 0) {
//                $money = $data['money'];
//                $word = "签到成功，奖励" . $data['money'] . "积分！";
//                $maxDay = date('t', strtotime("" . date("Y") . "-" . date("m") . ""));
//                // $maxDay = 2;
//                if ($maxDay == date("d") && $config['monthSign']) {
//                    $start = strtotime(date("Y-m-01 00:00:00"));
//                    $end = time();
//                    $signMonthNum = M('sign')->where("addtime between " . $start . " AND " . $end . " AND uid = " . session('userid') . " AND status = 0")->count();
//                    if ($signMonthNum == $maxDay) {
//                        $word .= "<p style='margin:10px 0 0'>连续签到一月，奖励<b class='red'>" . $config['points_monthsign'] . "</b>" . $config['coin'] . "</p>";
//                        $money = $money + $config['points_monthsign'];
//                        $data2['money'] = $config['points_monthsign'];
//                        $data2['addtime'] = $start;
//                        $data2['status'] = 1;
//                        $data2['uid'] = session('userid');
//                        M('sign')->add($data2);
//                        addLog("day_sign", $data2['money'], session("userid"), "连续签到一月获得" . $data2['money'] . "积分", 5, 1);
//                    }
//                }
                M('user')->where("id=" . session('userid') . "")->setInc('money', $data['money']); //setInc加
            }
        } else {
            $word = "签到失败！";
        }
        echo $word;
    }

    public function addQuestions() {
        $data['content'] = I("post.content");
        $arr = explode("#", $data['content']);
        if (count($arr) == 3) {
            $data['content'] = trim($arr[2]);
            $data['pid'] = intval($arr[1]);
        }
        $data['addtime'] = time();
        $data['uid'] = session("userid");
        if ($data['uid'] == '') {
            if (session("uid2") == '') {
                $data['uid2'] = rand(10000, 99999);
            } else {
                $data['uid2'] = session("uid2");
            }
        }
        M("questions")->add($data);
    }

    public function fastOrder() {
        $id = I("post.id", 0, 'int');
        $order = M("order")->field("addtime,sid")->where("id = " . $id . "")->find();
        $shop = M("shop")->field("sendtime")->where("id = " . $order['sid'] . "")->find();
        if ($shop['sendtime'] == 0) {
            $shop['sendtime'] = 20;
        }
        if ($order['addtime'] + $shop['sendtime'] * 60 > time()) {
            echo $shop['sendtime'];
        }
    }

    public function saveComment() {
        $config = getTableConfig();
        $id = I("post.id", 0, 'int');
        $comment = M("comment")->field("uid")->where("sid = " . $id . "")->find();
        if (!empty($comment)) {
            echo -1;
            exit;
        }
        $order = M("order")->field("sid")->where("id = " . $id . "")->find();
        $data['full'] = I("post.full", 5, 'int');
        $data['speed'] = I("post.speed", 5, 'int');
        $data['delicious'] = I("post.delicious", 5, 'int');
        $data['comment'] = I("post.comment");
        $data['commentTime'] = time();
        $score = ($data['full'] + $data['speed'] + $data['delicious']) / 3 * 2;
        $data['sid'] = $order['sid'];
        $data['orderid'] = $id;
        $data['uid'] = session("userid");
        $data['addtime'] = time();
        $data['points'] = $config['points_comment'];
        $lastid = M("comment")->add($data);
        if ($lastid > 0) {
            $shop = M("shop")->field("star")->where("id = " . $order['sid'] . "")->find();
            $star = round(($score + $shop['star']) / 2);
            M("shop")->where("id = " . $order['sid'] . "")->save(array("star" => $star));
            M("user")->where("id =" . session("userid") . "")->setInc('money', $config['points_comment']);
            addLog("comment_order", $config['points_comment'], session("userid"), "评价订单获得" . $config['points_comment'] . "积分", 5, 1);
            echo $config['points_comment'];
        }
    }

    public function orderFind() {
        $phone = I("post.phone");
        $today = strtotime(date("Y-m-d 00:00:00"));
        $now = time();
        $lists = M("order")->where("phone = '" . $phone . "' AND addtime between " . $today . " AND " . $now . " AND state in(0,1,9)")->order("id desc")->select();
        //   echo M("order")->getlastsql();
        foreach ($lists as $k => $v) {
            $lists[$k]['addtime'] = date("Y-m-d H:i");
            $lists[$k]['state'] = getOrderState($v['state']);
            $lists[$k]['shop'] = "<a target='_blank' href='" . U('Area/detail', array("id" => $v['sid'])) . "'>" . getSingleField($v['sid'], 'shop', 'name') . "</a>";
            if (in_array($v['state'], array(0, 1))) {
                //   $cancel = "<a target='_blank' style=text-decoration: underline;color:#666 id=cancel_" . $v['id'] . " data-func=cancelOrder('" . $v['id'] . "') onclick=confirmBox($(this),'您确定要取消当前订单吗？')>取消订单</a>";
                $message = M("messages")->where("orderid = '" . $v['id'] . "'")->find();
                if (!$message) {
                    $cuidan = "<a target='_blank' class='white br4 shadow call' href=" . U('Area/messages', array('id' => $v['sid'], 'mtype' => $v['id'])) . ">催单</a>";
                } else {
                    $cuidan = "<span style='color:red'>已催单</span>";
                }
                $lists[$k]['operate'] = $cuidan;
            } else {
                if ($v['reason']) {
                    $lists[$k]['state'] .= "<p>失效原因：<span style='color:red'>" . $v['reason'] . "</span></p>";
                }
                $lists[$k]['operate'] = "";
            }
        }
        echo json_encode($lists);
    }

    public function cancelOrder() {
        $id = I("post.id", 0, 'int');
        $data['state'] = 9;
        $data['reasonTime'] = time();
        $data['reason'] = "" . date("Y-m-d H:i:s", $data['reasonTime']) . "用户自己取消订单。";
        if (session("order") > 0) {
            M("order")->where("id = " . $id . " AND orderUid = " . session("order") . " AND state = 0")->save($data);
        } else {
            M("order")->where("id = " . $id . " AND uid = " . session("userid") . " AND state = 0")->save($data);
        }
        cancelOrder($id);
    }

    public function addMessages() {
        $data['content'] = I("post.content");
        $arr = explode("#", $data['content']);
        $mtype = I("post.mtype", 0, 'int'); //订单id
        if (count($arr) == 3) {//回复
            $data['content'] = trim($arr[2]);
            $data['pid'] = intval($arr[1]);
        } else {
            if ($mtype > 0) {
                $three = json_decode(getTableField("shortMessage", "three"), true);
                
                if ($three['order_find_receiver']) {
                    
                    $order_find_receiver = explode(",",$three['order_find_receiver']);
                    $phoneArr = array();
                    if(in_array(1,$order_find_receiver)){
                        $order = M("order")->field("sid")->where("id = '" . $mtype . "'")->find();
                        $shop = M("shop")->field("phone,is_start_phone")->where("id = '" . $order['sid'] . "'")->find();
                        if($shop['is_start_phone'] == 1){
                        array_push($phoneArr,$shop['phone']);
                        }
                    }
                    if(in_array(2,$order_find_receiver) && !empty($three['phones'])){
                      foreach(explode(",",$three['phones']) as $v){
                               array_push($phoneArr,$v);
                           }
                    }
                      
                    $message = M("messages")->field("id")->where("orderid = '" . $mtype . "'")->find();
                    if (empty($message) && !empty($phoneArr)) {
                        sendMobile(implode(",",$phoneArr), $data['content'], 'order_find');
                    }
                }
            }
        }
        $data['uid'] = session("userid");
        $data['addtime'] = time();
        $data['sid'] = I("post.sid");
        $data['orderid'] = $mtype;
        M("messages")->add($data);
    }

    public function getGiftsConfirm() {
        $data['uid'] = session("userid");
        if ($data['uid'] > 0) {
            $data['gid'] = I("post.id", 0, 'int');
            $user = M("user")->field("money")->where("id = " . $data['uid'] . "")->find();
            $info = M("gifts")->field("title,points")->where("id = " . $data['gid'] . "")->find();
            if ($user['money'] < $info['points']) {
                echo -2;
                exit;
            }
            $data['truename'] = I("post.truename");
            $data['addr'] = I("post.addr");
            $data['phone'] = I("post.phone");
            $data['title'] = $info['title'];
            $data['points'] = $info['points'];
            $data['addtime'] = time();
            $lastid = M("gifts_exchange")->add($data);
            if ($lastid > 0) {
                addLog("points_exchange", $info['points'], $data['uid'], "积分兑换消费" . $info['points'] . "积分", 5, 0);
                M("user")->where("id=" . session("userid") . "")->setDec('money', $info['points']);
            }
        } else {
            echo -1;
        }
    }

    public function award() {
        if (session("userid") > 0) {
            $user = M("user")->field("money")->where("id=" . session("userid") . "")->find();
            if ($user['money'] < 200) {
                echo json_encode(array("state" => -2));
                exit;
            }
            $lists = getTableFile('award');
            foreach ($lists as $k => $v) {
                $arr[$k + 1] = $v['percent'];
            }
            $rid = get_rand($arr); //根据概率获取奖项id 
            $award = $lists[$rid - 1]; //中奖项 

            $money = $award['pointsAward'];
            if ($money > 0) {
                addLog("draw", $money, session("userid"), "抽奖获得" . $money . "积分", 5, 1);
                M("user")->where("id=" . session("userid") . "")->setInc('money', $money);
            }
            $data['uid'] = session("userid");
            $data['gift_id'] = $award['id'];
            $data['gift_name'] = getSingleField($data['gift_id'], 'gifts', "title");
            $data['points'] = $award['pointsAward'];
            $data['addtime'] = time();
            M("gifts_award")->add($data);
            addLog("draw", 200, session("userid"), "抽奖消费200积分", 5, 0);
            M("user")->where("id=" . session("userid") . "")->setDec('money', 200);

            echo json_encode($award);
        } else {
            echo json_encode(array("state" => -1));
            session('returnUrl', U("Gifts/award"));
        }
    }

    public function checkCode() {
        $code = I('post.code');
        if (strtolower($code) == $_SESSION["helloweba_gg"]) {
            echo "true";
        } else {
            echo "false";
        }
    }

    public function getArea() {
        $pid = I("post.id", 0, 'int');
        $citys = getSub('area', $pid);
        // print_r($citys);
        echo json_encode($citys);
    }

    public function getCircleSub() {
        $pid = I("post.id", 0, 'int');
        $buildsArr = getSub('build', $pid);
        foreach ($buildsArr as $v) {
            if ($v['mtype'] == 0) {
                $sub[] = $v;
            }
        }
        echo json_encode($sub);
    }

    public function say() {
        $data['pid'] = I("post.id");
        $data['uid'] = session("userid");

        $data['content'] = I("post.con");
        $data['addtime'] = time();
        $t = time() - 20;
        $info = M("say")->field("content")->where("uid = " . $data['uid'] . " AND addtime >" . $t . " AND content = " . $data['content'] . "")->find();
        if (!$info) {
            M("say")->add($data);
        }
    }

    public function checkPwd() {
        $pwdOld = I('post.pwdOld');
        $info = M("user")->field("id")->where("id = '" . session('userid') . "' AND pwd = '" . md5($pwdOld) . "'")->find();
        // echo $Dao->getLastSql();
        if (empty($info)) {
            echo "false";
        } else {
            echo "true";
        }
    }

    public function moreDel() {
        $ids = $_POST['ids'];
        if (!empty($ids)) {
            $ids = explode(",", $ids);
            $table = I("post.table");
            foreach ($ids as $v) {
                if ($table == 'area') {
                    delArea($v);
                }
                M($table)->where("id = " . $v . "")->limit(1)->delete();
            }
        }
    }

    public function checkName() {
        $name = I('post.name');
        $info = M("user")->where("name='" . $name . "'")->find();
        if (empty($info)) {
            echo "true";
        } else {
            echo "false";
        }
    }

    public function checkEmail() {
        $email = I('post.email');
        $info = M("user")->where("email='" . $email . "'")->find();
        if (empty($info)) {
            echo "true";
        } else {
            echo "false";
        }
    }

    public function checkMobile() {
        $mobile = I('post.mobile');
        $info = M("user")->where("mobile='" . $mobile . "' AND id != '" . session('userid') . "'")->find();
        if (empty($info)) {
            echo "true";
        } else {
            echo "false";
        }
    }

    public function checkLoginPwd() {
        $pwd = I('post.pwd');
        $name = I('post.name');
        $info = M("user")->field("id")->where("name = '" . $name . "'  AND pwd = '" . md5($pwd) . "'")->find();
        if (empty($info)) {
            echo -1;
        }
    }

}

?>